package com.example.jussi.hotfixdemo;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 记得在 Mainfest 里注册
 * 热修复包 compile 'com.alipay.euler:andfix:0.5.0@aar'
 */
public class MainActivity extends AppCompatActivity {
    private Button button, patchBtn;
    private TextView textView;
    private MyApplication app;
    private static final String APATCH_PATH = "Out.apatch";

    private final String pathString = "http://192.168.1.106/Out.apatch";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        app = (MyApplication) getApplication();
        button = (Button) findViewById(R.id.button);
        patchBtn = (Button) findViewById(R.id.getpathc);
        textView = (TextView) findViewById(R.id.textView2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText("APP出bug啦!");
                //textView.setText("已经修复bug啦!");
            }
        });

        patchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downloadPatch(pathString);
            }
        });
    }

    private void downloadPatch(final String path) {
        Toast.makeText(MainActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
        new Thread() {
            @Override
            public void run() {
                //已经抛弃使用，如果需要要在 gradle 里声明 android{useLibrary 'org.apache.http.legacy'}
                /*HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);
                HttpResponse response;*/
                try {
                    URL url = new URL(path);
                    HttpURLConnection client = (HttpURLConnection) url.openConnection();
                    InputStream is =  client.getInputStream();
                    int fileSize = Integer.parseInt(client.getContentLength() + "");
                    int downloadSize = 0;
                    /*response = client.execute(get);
                    //HttpEntity entity = response.getEntity();
                    int fileSize = Integer.parseInt(entity.getContentLength() + "");
                    int downloadSize = 0;
                    InputStream is = entity.getContent();*/
                    FileOutputStream fos = null;
                    if (is != null) {
                        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), APATCH_PATH);
                        fos = new FileOutputStream(file);
                        byte[] buf = new byte[1024];
                        int ch = -1;
                        while ((ch = is.read(buf)) != -1) {
                            fos.write(buf, 0, ch);
                            downloadSize += ch;
                        }

                        fos.flush();
                        if (fos != null) {
                            if (fileSize == downloadSize) {
                                sendMsg(0);
                            }
                            fos.close();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private Handler update_handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {
                    case 0:
                        //设置进度条最大值
                        Toast.makeText(MainActivity.this, "补丁下载完成", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            }
            super.handleMessage(msg);
        }
    };

    private void sendMsg(int flag) {
        Message msg = new Message();
        msg.what = flag;
        update_handler.sendMessage(msg);
    }
}